package ss.pku.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FileASTRequestor;

import ss.pku.Scope.SourceFileScope;

public class ASTUtil {

	/**
	 *  Use the creat asts method for binding
	 *  @author liangwei
	 * */
	public static ArrayList<SourceFileScope> createASTs(String path) {
		ArrayList<String> srcs = new ArrayList<String>();
		Set<String> srcPaths = new HashSet<String>();
		final ArrayList<SourceFileScope> result = new ArrayList<SourceFileScope>();
		FileASTRequestor requestor = new FileASTRequestor() {
			public void acceptAST(String sourceFilePath, CompilationUnit ast) {
				SourceFileScope src = new SourceFileScope(sourceFilePath, ast);
				result.add(src);
				GlobalContainer.srcs.put(src.getPackageName()+"."+src.getFileName(), src);
			}
		};
		
		File file = new File(path);
		getAllSrcFile(file, srcs, srcPaths);
		Map<String, String> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);

		ASTParser parser = ASTParser.newParser(AST.JLS3);
		String[] srcsArray = srcs.toArray(new String[0]);
		GlobalContainer.fsl=srcs;
		String[] srcPathsArray = srcPaths.toArray(new String[0]);
		GlobalContainer.psl=srcPaths;
		
		parser.setCompilerOptions(options);
		parser.setEnvironment(null, srcPathsArray, null, true);
		parser.setResolveBindings(true);
		parser.setStatementsRecovery(true);
		parser.setBindingsRecovery(true);
		parser.createASTs(srcsArray, null, new String[0], requestor, null);
		return result;
	}

	/**
	 *  Get all the source files and paths
	 *  @author liangwei
	 * */
	public static void getAllSrcFile(File dir, ArrayList<String> srcs,
			Set<String> srcPaths) {
		File[] files = dir.listFiles();

		for (File file : files) {
			if (file.isFile() && file.getAbsolutePath().endsWith(".java")) {
				srcs.add(file.getAbsolutePath());
				srcPaths.add(file.getParentFile().getAbsolutePath());
			} else if (file.isDirectory()) {
				getAllSrcFile(file, srcs, srcPaths);
			}
		}
	}
	
}
